package com.sangeng.services.impl;

import com.sangeng.controller.LoginUserController;
import com.sangeng.domin.LoginUser;
import com.sangeng.domin.ResponseResult;
import com.sangeng.domin.User;
import com.sangeng.mapper.UserMapper;
import com.sangeng.services.UserService;
import com.sangeng.utils.JwtUtil;
import com.sangeng.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User longiUser) {

        //AuthenticationManager进行用户认证
        UsernamePasswordAuthenticationToken auth =
                new UsernamePasswordAuthenticationToken(longiUser.getUserName(),longiUser.getPassword());
        Authentication authenticate = authenticationManager.authenticate(auth);
        if(Objects.isNull(authenticate)){
            throw  new RuntimeException("登陆失败");
        }

/**        //进行用户认证--个人垃圾版
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, longiUser.getUserName());
        queryWrapper.eq(User::getDelFlag,"0");
        User user = userMapper.selectOne(queryWrapper);
        if (Objects.isNull(user)){
            throw  new RuntimeException("用户不存在,请输入正确的用户名");
        }
        BCryptPasswordEncoder bc = new BCryptPasswordEncoder();
        boolean matches = bc.matches(longiUser.getPassword(), user.getPassword());
        if (matches == false){
            throw  new RuntimeException("密码错误");
        }*/

        //如果认证通过，生成jwt
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String  userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);

        //把完整的用户信息，存入redis
        redisCache.setCacheObject("login" + userId, jwt);
        //信息响应给前端
        HashMap<String, String> map = new HashMap<>();
        map.put(userId,jwt);

        return new ResponseResult<>(200,"登陆成功", map);
    }
}
